// 云函数模板
// 部署：在 cloud-functions/login 文件夹右击选择 “上传并部署”
const cloud = require('wx-server-sdk')
// 初始化 cloud
cloud.init()
const db = cloud.database()

//初始化的用户数据

exports.main = async (event, context) => {

  const wxContext = cloud.getWXContext()
  const initUserData = {
    _openid: wxContext.OPENID,
    username: event.username,
    nickName: event.username,
    sex: '我不告诉你',
    introduce: '欢迎各位 start',
    headPortrait: event.headPortrait,
    email: '',
    locked: false, // 账号是否冻结
    enabled: true,
    delFlag: false,
    createTime: new Date(),
    updateTime: new Date(),
  }
  let exportData = {}
  const openidResult = await db.collection('user').where({
    _openid: wxContext.OPENID
  }).get()
  //错误码
  const responseCode = await cloud.callFunction({
    name: 'code'
  })
  const responseCodeResult = responseCode.result
  if (openidResult.data.length !== 0) {
    //存在数据
    exportData = Object.assign({
      data: openidResult.data[0]
    }, responseCodeResult['00000'])
  } else {
    //数据库不存在此数据,添加到数据库
    const addResult = await db.collection('user').add({
      data: initUserData
    })
    const successData = Object.assign({
      data: initUserData
    }, responseCodeResult['00000'])
    exportData = addResult._id ? successData : responseCodeResult["A0100"]
  }
  return exportData
}